package cn.t.config;


import cn.t.constants.SystemProperties;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Slf4j
@Configuration
@EnableCaching
public class CacheConfig {

    @Autowired
    private SystemProperties systemProperties;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress(systemProperties.getRedisHost());
        if (StringUtils.hasText(systemProperties.getRedisPwd())) {
            singleServerConfig.setPassword(systemProperties.getRedisPwd());
        }
        singleServerConfig.setDatabase(systemProperties.getRedisDb());

        log.info("Redisson初始化完成");
        return  Redisson.create(config);
    }

    @Bean
    public CacheManager cacheManager() {
        return new RedissonSpringCacheManager(redissonClient());
    }
}
